package com.yanwq.sayhi.controller.article.fragment;


import android.app.Fragment;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yanwq.sayhi.R;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class PopupMenu {

    PopupWindow mPW;
    Context mContext;
    LinearLayout mLyt;

    private List<Item> mItemList;

    public PopupMenu(Context context, List<Item> itemList) {
        mContext = context;
        mItemList = itemList;
        mPW = new PopupWindow(makeView(), WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
    }

    public View makeView() {
        ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(mContext).inflate(R.layout.fragment_menu, null);
        mLyt = (LinearLayout) viewGroup.findViewById(R.id.menu_lyt);

        for (final Item item : mItemList) {
            if (item.checkValue()) {
                throw new RuntimeException("Illegal item param.");
            }

            View menuItem = LayoutInflater.from(mContext).inflate(R.layout.item_menu, null);

            TextView textView = (TextView) menuItem.findViewById(R.id.menu_text);
            textView.setText(item.text);
            textView.setCompoundDrawablesWithIntrinsicBounds(item.drawable, 0, 0, 0);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    item.listener.onClick(v);
                    mPW.dismiss();
                }
            });
            mLyt.addView(menuItem);
        }

        return viewGroup;
    }

    public PopupWindow getPopupWindow() {
        return mPW;
    }

    public static class Item {
        int drawable;
        String text;
        View.OnClickListener listener;

        public Item(int drawable, String text, View.OnClickListener listener) {
            this.drawable = drawable;
            this.text = text;
            this.listener = listener;
        }

        public boolean checkValue() {
            return drawable == 0 || text == null || listener == null;
        }
    }
}
